'''
Created on 2014. 6. 2.

@author: leeinsup
'''

import _thread
from socket import *
from xmlbook import *
from http.server import BaseHTTPRequestHandler, HTTPServer
from http.client import HTTPConnection
import xml.dom.minidom


myHost = 'localhost'
myPort = 9999

class chatServer():
    threads = []
    sockobj = socket(AF_INET, SOCK_STREAM)
    sockobj.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    sockobj.bind((myHost, myPort))
    sockobj.listen(5)
    clients = dict()
    regKey = '5432211430547460eb22062cde0b1a74'
    server = "openapi.naver.com"
    conn = None
    
    def userURIBuilder(self, server, **user):
        str = "http://" + server + "/search" + "?"
        for key in user.keys():
            str += key + "=" + user[key] + "&"
        return str

    def connectOpenAPIServer(self):
        self.conn = HTTPConnection(self.server)
    
    def getMovieDataFromKeyword(self, keyword):
        if self.conn == None:
            self.connectOpenAPIServer()
        uri = self.userURIBuilder(self.server, key=self.regKey, query=keyword, display="10", start="1", target="movie")
        self.conn.request("GET", uri)
        req = self.conn.getresponse()
        print('\n')
        if int(req.status) == 200 :
            data = req.read()
            dom = xml.dom.minidom.parseString(data)
            return self.extractMovieData(dom.toxml())
        else :
            print ("OpenAPI request has been failed!! please retry")
            return None

    def getMovieDataFromDirector(director):
        if self.conn == None :
            connectOpenAPIServer()    
        uri = self.userURIBuilder(self.server, key=self.regKey, query=director, display="10", start="1", target="movie")
        req = self.conn.getresponse()
        print('\n')
        if int(req.status) == 200 :
            data = req.read()
            dom = xml.dom.minidom.parseString(data)
            return self.extractMovieData(dom.toxml())
        else :
            print ("OpenAPI request has been failed!! please retry")
            return None

    def extractMovieData(self, strXml):
        import xml.etree.ElementTree as ET
        root = ET.fromstring(strXml)
        result = ''
        for element in root.iter("item"):
            strTitle = element.find("title").text
            #directorName = element.find("director").text
            userRate = element.find("userRating").text
            result += strTitle + "|" + "|" + userRate  + "|" + "\n"
            #print("Title is ", strTitle)
        return result

    def removeClient(self, connection):
        del self.clients[connection.fileno()]
        self.threads.remove(connection)

    def handleClient(self, connection):
        #time.sleep(5)
        self.threads.append(connection)
        while True:
            data = connection.recv(1024)
            if not data: break
            sendMsg = self.getMovieDataFromKeyword(data.decode())
            connection.send(sendMsg.encode())
        connection.close()
        
        
    def setUser(self, connection, user):
        self.clients[connection.fileno()] = [connection, user]

    def dispatcher(self):
        while True:
            connection, address = self.sockobj.accept()
            print('Server connected by', address)
            _thread.start_new_thread(self.handleClient, (connection,))

if __name__ == '__main__':
    server = chatServer()
    server.dispatcher()

